package net.linku.config;

import cn.hutool.json.JSONUtil;
import net.linku.exception.CustomExceptionTranslator;
import net.linku.filter.CustomClientCredentialsTokenEndpointFilter;
import net.linku.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * 授权服务器配置类。
 * 扩展 AuthorizationServerConfigurerAdapter 以提供自定义的 OAuth2 配置。
 * 包括客户端详细信息配置、令牌存储配置和安全配置。
 *
 * 作者: SilenceTian
 * 日期: 2024/6/23
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Qualifier("userServiceDetailsServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 配置可以访问授权服务器的客户端。
     *
     * @param clients 客户端详细信息配置器
     * @throws Exception 配置过程中发生的异常
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("linku-api")
                .secret(passwordEncoder.encode("linku-secret"))
                .scopes("all")
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(3600) // 1小时有效期
                .refreshTokenValiditySeconds(30 * 24 * 3600) // 30天刷新期
                .and()
                .withClient("inside-app")
                .secret(passwordEncoder.encode("inside-secret"))
                .authorizedGrantTypes("client_credentials")
                .scopes("all")
                .accessTokenValiditySeconds(Integer.MAX_VALUE); // 永不过期
    }

    /**
     * 配置授权服务器的端点。
     *
     * @param endpoints 授权服务器端点配置器
     * @throws Exception 配置过程中发生的异常
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(jwtTokenStore())
                .tokenEnhancer(jwtAccessTokenConverter())
                .exceptionTranslator(new CustomExceptionTranslator()); // 添加自定义异常处理器
    }

    /**
     * 定义 JWT 令牌存储的 Bean。
     *
     * @return JWT 令牌存储
     */
    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 定义 JWT 访问令牌转换器的 Bean。
     *
     * @return JWT 访问令牌转换器
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        ClassPathResource classPathResource = new ClassPathResource("linku.jks");
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "linku123".toCharArray());
        tokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("linku", "linku123".toCharArray()));
        return tokenConverter;
    }

    /**
     * 配置授权服务器的安全设置。
     *
     * @param security 授权服务器安全配置器
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        // 自定义客户端凭证过滤器
        CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security);
        endpointFilter.afterPropertiesSet(); // 初始化过滤器
        endpointFilter.setAuthenticationEntryPoint(authenticationEntryPoint()); // 设置自定义认证入口点
        security.addTokenEndpointAuthenticationFilter(endpointFilter); // 添加自定义过滤器

        // 配置安全设置
        security.authenticationEntryPoint(authenticationEntryPoint()) // 设置自定义认证入口点
                .tokenKeyAccess("isAuthenticated()") // 只有认证用户才能访问 /oauth/token_key 端点
                .checkTokenAccess("permitAll()"); // 任何人都可以访问 /oauth/check_token 端点
    }

    /**
     * 定义认证入口点的 Bean，用于处理认证异常。
     *
     * @return 认证入口点
     */
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, e) -> {
            response.setStatus(HttpStatus.OK.value()); // 设置响应状态为 200 OK
            response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE); // 设置响应内容类型为 JSON
            response.setHeader("Access-Control-Allow-Origin", "*"); // 允许跨域
            response.setHeader("Cache-Control", "no-cache"); // 禁用缓存
            // 返回自定义错误信息
            Result result = new Result(HttpStatus.UNAUTHORIZED.value(), "Client authentication failed", null);
            response.getWriter().print(JSONUtil.toJsonStr(result)); // 将错误信息转换为 JSON 字符串并写入响应
            response.getWriter().flush();
        };
    }

}
